<?php
namespace app\controller\admin;

use app\BaseController;
use app\lib\Password;
use app\lib\response\JSON;
use app\model\Api as ModelApi;
use app\model\User;
use app\model\User as ModelUser;
use app\validate\User as UserValidator;
use Firebase\JWT\JWT;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Request;

class Common extends BaseController
{
    /**
     * 登录
     */
    public function login()
    {
        $params = Request::post();
        try {
            validate(UserValidator::class)
                ->scene('login')
                ->check($params);
        } catch (ValidateException $e) {
            return JSON::error($e->getMessage());
        }
        $user = User::where('username',$params['username'])->find();
        if(!$user){
            return JSON::error("用户名不存在");
        }
       
        if( !Password::verify($params['password'],$user->password) ){
            return JSON::error("密码错误");
        }

        $user->last_login_time = ftime();
        $user->last_login_ip = Request::ip();
        $user->save();

        //生成token
        $key = Config::get('app.jwt_key');
        $expire = Config::get('app.jwt_expire');
        $token = [
            "iss"=>"",  //签发者 可以为空
            "aud"=>"", //面象的用户，可以为空
            "iat" => time(), //签发时间
            "nbf" => time()-10, //在什么时候jwt开始生效
            "exp" => time()+$expire, //token 过期时间
            "uid" => $user->id, //记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
            "username" => $user->username
        ];
        $token = JWT::encode($token,$key,"HS256"); //根据参数生成了 token

        return JSON::successData( [
            'token' => $token
        ]);
    }


     /**
     * 测试
     */
    public function test()
    {
        $t1 = millisecond();
        sleep(1);
        return millisecond()-$t1;
    }

    public function upload(){
        $request = request();
        // 获取表单上传文件 例如上传了001.jpg
        $file = $request->file('file');
        if (empty($file)) {
            return JSON::error("请选择要上传的文件");
        }
        try {
            validate(['image'=>'fileSize:10240|fileExt:jpg'])
                ->check([$file]);
        } catch (\think\exception\ValidateException $e) {
            echo JSON::error($e->getMessage());
        }
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('public')->putFile( 'avatar', $file);
        return JSON::successData([
            'url' => $request->domain() . '/storage/' . $savename
        ]);
    }
}
